﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.Speech.Recognition;
//using System.Speech.Synthesis;
using System.Threading;
using ScoreHelper.Properties;
namespace ScoreHelper
{
    public partial class frmMain : Form
    {
        protected ScoreManager smgr = null;
        protected DomProxy dProxy = null;
        //protected SpeechRcg sRcg = null;
        //private static SpeechRecognitionEngine SRE = new SpeechRecognitionEngine();
        public frmMain()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.Icon;
            wb.Navigate(Application.StartupPath + "\\" + Settings.Default.StartUrl);
            //wb.Navigate(Settings.Default.LoginUrl);
            tssStatus.Text = "正在打开登录页面，请稍候...";

            // 置初始状态

            smgr = new ScoreManager();
            dProxy = new DomProxy();
            dProxy.OnTemplateClick += llblTemplate_LinkClicked;
            dProxy.OnBrowseFile += btnBrowse_Click;
            //(wb.ActiveXInstance as SHDocVw.WebBrowser).NewWindow3 += new SHDocVw.DWebBrowserEvents2_NewWindow3EventHandler(Form1_NewWindow3);
            wb.Navigating += new WebBrowserNavigatingEventHandler(wb_Navigating);

            //smgr.ShowTemplate(null);
            //Thread t = new Thread(new ThreadStart(StartReg));
            //t.Start();
            //StartReg();
            
        }


        void Form1_NewWindow3(ref object ppDisp, ref bool Cancel, uint dwFlags, string bstrUrlContext, string bstrUrl)
        {
            Cancel = true;
            wb.Navigate(bstrUrl);
        }

        private void SetDocTarget(HtmlDocument doc, string target)
        {
            HtmlElementCollection links = doc.Links;

            for (int i = 0; i < links.Count; i++)
            {
                if (links[i].GetAttribute("target") == "_blank")
                {
                    links[i].SetAttribute("target", "_top");
                }
            }
        }

        //void StartReg()
        //{
        //    SRE.SetInputToDefaultAudioDevice();         //<=======默认的语音输入设备，你可以设定为去识别一个WAV文件。 
        //    GrammarBuilder GB = new GrammarBuilder();
        //    GB.Append("选择");
        //    GB.Append(new Choices(new string[] { "红色", "绿色" }));
        //    Grammar G = new Grammar(GB);
        //    G.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(G_SpeechRecognized);
        //    SRE.LoadGrammar(G);
        //    SRE.RecognizeAsync(RecognizeMode.Multiple); //<=======异步调用识别引擎，允许多次识别（否则程序只响应你的一句话） 
        //}

        //void G_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        //{
        //    Text = e.Result.Text;
            
        //    switch (e.Result.Text)
        //    {
        //        case "选择红色":
        //            BackColor = Color.Red;
        //            break;
        //        case "选择绿色":
        //            BackColor = Color.Green;
        //            break;
        //    }
        //} 
        

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = dProxy.CourseName + "成绩单";
            openFileDialog1.Filter = Settings.Default.FileExt;
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                llblFile.Tag = openFileDialog1.FileName;
                llblFile.Text = getMaskPath(llblFile.Tag.ToString());
                try
                {
                    if (smgr == null)
                        throw new Exception("你还没有登录，请先登录。");
                    if(dProxy.Courses.Count < 1)
                        throw new Exception("你所教课程列表为空。");
                    smgr.RefreshOption(dProxy.FrmOption);
                    tssStatus.Text = "正在检查成绩单格式...";
                    if (smgr.CheckFormat(llblFile.Tag.ToString()))
                    {
                        tssStatus.Text = "成绩单格式正确。";
                        dr = MessageBox.Show("成绩单格式正确，是否开始录入成绩？",
                            "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            // 开始填充
                            btnFill_Click(sender, e);
                        }
                    }
                    else
                    {
                        throw new Exception("成绩单格式不正确。");
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    tssStatus.Text = ex.Message;
                    dr = MessageBox.Show(ex.Message + "\n 成绩单格式不正确，是否查看模板文件？",
                            "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        // 查看模板
                        llblTemplate_LinkClicked(sender, e);
                    }
                }
            }
        }

        private string getMaskPath(string path)
        {
            return getMaskPath(path, 40);
        }

        private string getMaskPath(string path, int maxLen)
        {
            string fName = path.Substring(path.LastIndexOf('\\'));
            string mPath = "";
            if (maxLen - fName.Length > 3)
            {
                if (maxLen - fName.Length - 3 < path.Length)
                {
                    mPath = path.Substring(0, maxLen - fName.Length - 3) + "..." + fName;
                }
                else
                {
                    mPath = path;
                }
            }
            else
            {
                mPath = fName;
            }
            return mPath;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 加密
            //Settings.Default.Password = dProxy.Password;
            if(!string.IsNullOrEmpty(dProxy.User))
                Settings.Default.UserID = dProxy.User;
            Settings.Default.Save();
            smgr = null;
            dProxy = null;
            //if (sRcg != null)
            //{
            //    sRcg.Dispose();
            //    sRcg = null;
            //}
        }

        private void llblTemplate_LinkClicked(object sender, EventArgs e)
        {
            if (smgr == null || dProxy == null 
                || dProxy.FrmOption == null || dProxy.FrmOption.Children.Count < 1)
            {
                MessageBox.Show("你还没有登录，请先登录。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            smgr.RefreshOption(dProxy.FrmOption);
            smgr.ShowTemplate(dProxy.FrmScore);
        }

        private void llblFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (llblFile.Tag == null)
                return;
            try
            {
                System.Diagnostics.Process.Start(llblFile.Tag.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(/*ex.TargetSite + " 引发了错误：\n\t" + */ ex.Message + llblFile.Tag.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void wb_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            tssProcess.Visible = true;
            if ((e.CurrentProgress > 0) && (e.MaximumProgress > 0))
            {
                tssProcess.Maximum = Convert.ToInt32(e.MaximumProgress);
                tssProcess.Step = Convert.ToInt32(e.CurrentProgress);
                tssProcess.PerformStep();
            }
            else if (wb.ReadyState == WebBrowserReadyState.Complete)
            {
                tssProcess.Value = 0;
                tssProcess.Visible = false;
            } 
        }

        void wb_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            if (dProxy.CurStatus == DomProxy.OperationStatus.Ready
                || dProxy.CurStatus == DomProxy.OperationStatus.LoginFailed) // 获取登录名和密码
            {
                dProxy.SaveUserInfo(wb.Document);
            }
        }

        private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            SetWndCaption(wb.Document.Title);
            if (dProxy == null)
                return;

            HtmlDocument fDoc = wb.Document;
            DomProxy.OperationStatus LastStatus = dProxy.LastStatus;
            DomProxy.OperationStatus CurStatus = dProxy.ParseStatus(fDoc, e.Url.ToString());
            int tx = wb.Width / 2 + 100;
            int ty = 100;
            toolTip1.Hide(wb);
            Uri url;
            string tempUrl;
            switch (CurStatus)
            {
                case DomProxy.OperationStatus.Ready:
                    tssStatus.Text = "输入用户名密码登录。";
                    dProxy.SetSavedUser(Settings.Default.UserID, Settings.Default.Password, fDoc);
                    ty = 150;
                    break;
                case DomProxy.OperationStatus.LoginFailed:
                    
                    tssStatus.Text = "登录失败，请重新登录。";
                    MessageBox.Show(fDoc.Body.InnerText,
                            "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    wb.Navigate(Application.StartupPath + "\\" + Settings.Default.StartUrl);
                    //wb.Navigate(Settings.Default.LoginUrl);
                    break;
                case DomProxy.OperationStatus.Login:
                    if (LastStatus == DomProxy.OperationStatus.Ready 
                        || LastStatus == DomProxy.OperationStatus.LoginFailed
                        || LastStatus == DomProxy.OperationStatus.Printing)
                    {
                        tssStatus.Text = "登录成功，转向录入系数页面...";
                        tempUrl = String.Format(Settings.Default.FactorUrl, dProxy.User);
                        url = new Uri(wb.Url, tempUrl);
                        wb.Navigate(url, Settings.Default.FrameMain);

                        //System.Windows.Controls.PrintDialog printDialog = new PrintDialog();
                        //printDialog.PrintDocument(((IDocumentPaginatorSource)browser.Document).DocumentPaginator, "My App"); 
                    }
                    break;
                case DomProxy.OperationStatus.FillFactor:

                    if (LastStatus == DomProxy.OperationStatus.FillFactor) // 已保存
                    {
                        tssStatus.Text = "成绩系数已保存，请选择课程录入成绩。";
                        tx = 100;
                        ty = 300;
                        
                        //MessageBox.Show("成绩系数已保存，请在左侧点击课程录入成绩。\n**注意平时成绩和期末成绩的选择。",
                        //    "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        tssStatus.Text = "成绩系数。";
                    }
                    // 提取更新各个课程的系数设置
                    break;
                case DomProxy.OperationStatus.FillScore:
                    tbcPanel.SelectedIndex = 1;
                    tssStatus.Text = "请下载成绩单模板 或者 选择成绩单录入成绩。";
                    timer1.Enabled = true;
                    ty = 30;
                    break;
                case DomProxy.OperationStatus.Printing:
                    string[] printUrlText = new string[] { "成绩登记表，请选择份数2份", "成绩统计表，请选择份数1份", "成绩分析报告，请选择页码1页，份数1份" };
                    tssStatus.Text = "正在打印..." + printUrlText[dProxy.PrintIndex];
                    ty = 50;
                    dProxy.Print(wb);
                    tempUrl = dProxy.NextPrintUrl;
                    if (!string.IsNullOrEmpty(tempUrl))
                        wb.Navigate(tempUrl);
                    else
                    {
                        // 跳到成绩系数
                        dProxy.EndPrint();
                        url = new Uri(wb.Url, Settings.Default.FrameUrl);
                        wb.Navigate(url);
                    }
                    break;
                case DomProxy.OperationStatus.Finished:
                    // 打印成绩单及统计表等信息
                    // 改变连接对象，保证在当前页打开
                    tssStatus.Text = "成绩已保存。";
                    if (LastStatus != DomProxy.OperationStatus.Printing)
                    {
                        DialogResult dr = MessageBox.Show("成绩已提交，是否开始打印相关报表？\n" +
                                    "其中，成绩登记表打印2份，成绩统计表打印1份，\n成绩分析报告（图表）仅打印第1页，1份。" +
                                    "\n\n**打印前请确认打印机已连接。",
                                "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                        if (dr == DialogResult.Yes)
                        {
                            tssStatus.Text = "正在准备打印...";
                            dProxy.PreparePrint();
                            wb.Navigate(dProxy.NextPrintUrl);
                        }
                    }
                    break;
                case DomProxy.OperationStatus.Quit:
                    if (MessageBox.Show("已退出系统，现在退出程序吗？", "提示",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Application.Exit();
                    }
                    else
                    {
                        tssStatus.Text = "就绪";
                        wb.Navigate(Application.StartupPath + "\\" + Settings.Default.StartUrl);
                        tbcPanel.SelectedIndex = 0;
                    }
                    break;
                case DomProxy.OperationStatus.Error:
                    tssStatus.Text = "状态错误，打开了不期望的页面。";
                    break;
                case DomProxy.OperationStatus.ChangePassword:
                    tssStatus.Text = "修改密码。";
                    break;
                default:
                    break;
            }
            
            toolTip1.Show(tssStatus.Text, wb, tx, ty, 5000);
        }

 


        private void OnFilledItem(int Current, int Total, int FilledCount)
        {
            //tssStatus.Text = "正在填充成绩..." + (Current * 100 / Total) + "%  已填充：" + FilledCount + " 失败：" + (Current - FilledCount);
            timer1.Tag = "filling";
            timer1.Enabled = false;
            if (Total <= 0)
                return;
            tssStatus.Text = string.Format("正在录入成绩...{0}/{1} (进度：{2}%，  已完成：{3}； 失败：{4})", Current, Total, (Current * 100 / Total), FilledCount, (Current - FilledCount));
            tssProcess.Visible = true;
            tssProcess.Maximum = Total;
            tssProcess.Step = 1;
            tssProcess.PerformStep();
        }

        private bool OnFilledFinish(int Total, int FilledCount)
        {
            timer1.Tag = null;
            tssProcess.Value = 0;
            tssProcess.Visible = false;
            return (MessageBox.Show("全部完成录入，共" + Total + "人， 成功：" + FilledCount + "，失败：" + (Total - FilledCount) + "\n 现在查看录入报告吗？",
                "完成",  MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes);
        }

        private void SetWndCaption(string Title)
        {
            if (Title.Length < 1)
                return;
            int i = this.Text.IndexOf(" - ");
            if (i < 0)
                this.Text = Title + " - " + this.Text;
            else
                this.Text = Title + " - " + this.Text.Substring(i + 3);
        }


        private void btnFill_Click(object sender, EventArgs e)
        {
            try
            {
                if (smgr == null || dProxy == null)
                    throw new Exception("你还没有登录，请先登录。");
                if (smgr.OneItemFilled == null)
                    smgr.OneItemFilled = new ScoreManager.ItemFilled(OnFilledItem);
                if (smgr.OnFinish == null)
                    smgr.OnFinish = new ScoreManager.FillFinished(OnFilledFinish);
                smgr.Fill(llblFile.Tag.ToString(), dProxy.FrmScore);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tssStatus.Text = ex.Message;
            }

        }

        private void btnTempSave_Click(object sender, EventArgs e)
        {
            dProxy.FrmScore.InvokeMember("submit");
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            dProxy.FrmScore.InvokeMember("reset");
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            dProxy.FrmScore.All.GetElementsByName(Settings.Default.ScocreSubmitBtn)[1].InvokeMember("onclick");
        }

        private void btnBrowse2_Click(object sender, EventArgs e)
        {
            //openFileDialog1.FileName = llblFile.Tag.ToString();
            //openFileDialog1.Filter = Settings.Default.FileExt;
            //DialogResult dr = openFileDialog1.ShowDialog();
            //if (sRcg == null)
            //{
            //    sRcg = new SpeechRcg();
            //    sRcg.OnFinished += AllFinish;
            //    sRcg.OnSelected += SelectOne;
            //    sRcg.numDigit = Convert.ToInt32(nudDigit.Value);
            //    sRcg.Follow = chkFollow.Checked;
            //}

            //if (dr == DialogResult.OK)
            //{
            //    btnBrowse2.Tag = openFileDialog1.FileName;
            //    try
            //    {
            //        tssStatus.Text = "正在检查名单格式...";
            //        if (sRcg.CheckFormat(btnBrowse2.Tag.ToString()))
            //        {
            //            tssStatus.Text = "名单符合要求。";
            //            btnRec.Enabled = true;
            //        }
            //        else
            //        {
            //            throw new Exception("名单格式不正确，至少包含学号和姓名相邻两列。");
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //        tssStatus.Text = ex.Message;
            //    }
            //}
        }

        // 语音部分

        private delegate void CtrlDelegate(object sender, string args);
        private void SelectOne(object sender, string args)
        {
            CtrlDelegate cd = new CtrlDelegate(Select1);
            lblCurNum.Invoke(cd, new object[] { sender, args });
            //lblCurNum.Text = sender.ToString() + ":" + args;
        }
        private void Select1(object sender, string args)
        {
            lblCurNum.Text = sender.ToString() + ":" + args;
            
        }
        private void AllFinish(object sender, string args)
        {
            CtrlDelegate cd = new CtrlDelegate(RcgFinish);
            btnRec.Invoke(cd);
        }
        private void RcgFinish(object sender, string args)
        {
            btnRec.Text = btnRec.Text.Replace("保存", "开始");
            //sRcg.Stop();
            btnBrowse2.Enabled = true;
            
            tssStatus.Text = "成绩已保存！";
        }

        private void btnRec_Click(object sender, EventArgs e)
        {
            //if (sRcg == null)
            //    return;
            //if (btnRec.Text.IndexOf("开始")>-1)
            //{
            //    if (sRcg.Running)
            //        return;
                
            //    btnRec.Text = btnRec.Text.Replace("开始", "停止");
            //    sRcg.Start();
            //    btnBrowse2.Enabled = false;
            //    btnPre.Enabled = true;
            //    btnNext.Enabled = true;
            //    tssStatus.Text = "请打开麦克风和耳机，正在进行语音录入...";

            //}
            //else
            //{
            //    if (!sRcg.Running)
            //        return;
            //    btnRec.Text = btnRec.Text.Replace("停止", "开始");
            //    sRcg.Stop();
            //    btnBrowse2.Enabled = true;
            //    btnPre.Enabled = false;
            //    btnNext.Enabled = false;
            //    tssStatus.Text = "成绩已保存！";

            //}
        }

        private void btnPre_Click(object sender, EventArgs e)
        {
            //if (sRcg == null)
            //    return;
            //sRcg.MovePrevious();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            //if (sRcg == null)
            //    return;
            //sRcg.MoveNext();
        }

        private void tssStatus_TextChanged(object sender, EventArgs e)
        {
            if(timer1.Tag == null)
                timer1.Enabled = true;

        }

        private int colorIndex = 0;
        private Color[] flashColors = new Color[] {Color.FromName("ControlText"),
            Color.Red, Color.Blue, Color.Lime,
            Color.Magenta, Color.Yellow, Color.Cyan,
            Color.Maroon, Color.Navy, Color.Green};
        private void timer1_Tick(object sender, EventArgs e)
        {
            colorIndex++;
            if (colorIndex >= flashColors.Length)
            {
                timer1.Enabled = false;
                colorIndex = 0;
            }
            tssStatus.ForeColor = flashColors[colorIndex];
        }

        private void tssStatus_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(tssStatus.Text, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            toolTip1.Show(tssStatus.Text, statusStrip1, 10, -30); 
            //toolTip1.SetToolTip(wb, tssStatus.Text);
        }

    }
}
